from myapp import db
from datetime import datetime
from flask import jsonify


class Resource(db.Model):
    __tablename__ = 'sys_resource'
    __mapper_args__ = {
     #"order_by": 'seq'
    }
    id = db.Column(db.String(36), primary_key=True)
    create_time = db.Column(db.DateTime, index=True, default=datetime.now)
    update_time = db.Column(db.DateTime, index=True, default=datetime.now)
    name = db.Column(db.String(100))
    url = db.Column(db.String(200))
    path = db.Column(db.String(200))
    perms = db.Column(db.String(150))
    description = db.Column(db.String(200))
    iconcls = db.Column(db.String(100))
    seq = db.Column(db.Integer)
    target = db.Column(db.String(100))

    resource_type_id = db.Column(db.String, db.ForeignKey('sys_resource_type.id'))

    resource_id = db.Column(db.String, db.ForeignKey('sys_resource.id'))

    children = db.relationship('Resource', backref=db.backref('parent', remote_side=[id]),
                               lazy='dynamic', order_by="Resource.seq")

    status = db.Column(db.String(10))

    hidden = False

    def get_id(self):
        return str(self.ID)

    def to_json(self):
        return {
            'menuId': self.id,
            'createTime': self.create_time,
            'updateTime': self.update_time,
            'menuName': self.name,
            'component': self.url,
            'description': self.description,
            'icon': self.iconcls,
            'orderNum': self.seq,
            'target': self.target,
            'parentId': self.get_pid(),
            'resourceType': self.get_type_json(),
            'status': self.status,
            'visible': '0',
            'isFrame': '1',
            'path': self.path,
            'perms': self.perms,
            'isCache': '1',
            # 类型（M目录 C菜单 F按钮）
            'menuType': 'F' if self.resource_type_id == '1' else 'C' if self.resource_type_id == '0' else 'M'
        }

    def to_tree_select_json(self):
        return {
            'id': self.id,
            'label': self.name,
            'children': [res.to_tree_select_json() for res in self.children]
        }

    def to_router_json(self):
        router = {
            'name': self.path.capitalize() if self.path else '',
            'path': self.path,
            'hidden': self.hidden,
            'redirect': 'noRedirect',
            'component': self.url,
            'alwaysShow': True,
            'meta': {
                'title': self.name,
                'icon': self.iconcls,
                'noCache': False,
                'link':''
            },
            'children': [
                res.to_router_json() for res in self.children if res.type.id == '3' or res.type.id == '0'
            ]
        }

        if not router['children']:
            del router['children']
            del router['redirect']
            del router['alwaysShow']
        if not router['component']:
            router['component'] = 'Layout'

        return router

    def to_menu_json(self):
        return {
            'id': self.id,
            'iconCls': self.iconcls,
            'pid': self.get_pid(),
            'state': 'open',
            'checked': False,
            'attributes': {
                'target': self.target,
                'url': self.url
            },
            'text': self.name
        }

    def get_pid(self):
        if self.parent:
            return self.parent.id
        return ''

    def get_type_json(self):
        if self.type:
            return self.type.to_json()
        return {}

    def __repr__(self):
        return '<Resource name:%r url:%r>\n' %(self.name, self.url)